﻿/// <reference path="jquery-1.7.1.min.js" />
/// <reference path="jquery.jplayer.min.js" />
/// <reference path="jquery.jplayer.playlist.min.js" />
/// <reference path="waypoints.min.js" />


$(function () {
	$('.play-song').live('click', function () {
		playSong(this);
		return false;
	});

	$('[class*=set-rate]').live('click', function () {
		setRate(this);
		return false;
	});

	$('.more').waypoint(function () {
		loadPage(this);
		return false;
	}, { offset: '100%' });

});

function showError(text) {
	alert(text);
}

function loadPage(obj) {

	$(obj).waypoint('remove');

	var url = $(obj).data('list-url');
	var containerId = $(obj).data('container-id');
	var page = $(obj).data('next-page');

	var container = $('#' + containerId);

	$.ajax({
		url: url,
		data: { page: page },
		dataType: 'html',
		success: function (html) {

			if (html) {
				var list = $(html);
				container.append(list);

				$(obj).data('next-page', page + 1);

				$(obj).waypoint({ offset: '100%' });
			} else {
				$(obj).hide();
			}
		}
	});

}

function setRate(obj) {
	var setRateUrl = $(obj).data('set-rate-url');

	$.ajax({
		url: setRateUrl,
		type: 'POST',
		dataType: 'json',
		cache: false,
		success: function (data) {

			var parent = $(obj).parents('.rate-buttons');
			var menu = parent.find('.dropdown-menu');

			$('[class*=set-rate]', menu).removeClass('selected');
			$(data.selector, menu).addClass('selected');

			var rateName = $(data.selector, menu).data('rate-name');
			$('a.dropdown-toggle span.rate-name', parent).text(rateName);
		},
		error: function (data) {
			showError(data.responseText);
		}
	});
}


function playSong(obj) {

	var playerId = $(obj).data('player-id');
	var controlContainerId = $(obj).data('controls-id');
	var url = $(obj).data('file-url');

	$('#' + playerId).jPlayer({
		ready: function () {
			$(this).jPlayer('setMedia', { mp3: url });
			$(this).jPlayer('play');
		},
		play: function () { // To avoid both jPlayers playing together.
			$(this).jPlayer('pauseOthers');
		},
		swfPath: '/music/Content/js', // todo: зарефакторить захардкоженые пути
		supplied: 'mp3',
		cssSelectorAncestor: '#' + controlContainerId,
		wmode: 'window'
	});

	$('#' + controlContainerId).show();
	$(obj).hide();
}

function initPlaylist(playerSelector, controlsContainerSelector, songs) {

	new jPlayerPlaylist(
		{
			jPlayer: playerSelector,
			cssSelectorAncestor: controlsContainerSelector
		},
		songs,
		{
			swfPath: '/music/Content/js', // todo: зарефакторить захардкоженые пути
			supplied: 'mp3',
			wmode: 'window'
		}
	);


}